package com.chen.controller;

import com.chen.dao.SalesmanDao;
import com.chen.model.Salesman;
import com.chen.model.User;
import com.chen.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;


import javax.servlet.http.HttpSession;


@Controller
@SessionAttributes("user")
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private SalesmanDao salesmanDao;

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/checkLogin")
    public String checkLogin(User user, Model model,HttpSession session){
        //调用service方法
        User uuu = user;
        user = userService.checkLogin(user.getUser_account(), user.getUser_password());
        //若有user则添加到model里并且跳转到成功页面
        if(user != null){
            session.setAttribute("user1",user);
            model.addAttribute("user",user);
            if (user.getUser_power()==0){
                return "index";
            }
            else if (user.getUser_power()==1){
                return "index1";
            }
//            return "redirect:/customer/findAllCustomer";

//            return "forward:/customer/findAllCustomer";
        }
        else{
            Salesman  salesman;
            salesman = salesmanDao.findByAccount(uuu.getUser_account());
            if(salesman!=null){
                if(salesman.getSalesman_password().equals(uuu.getUser_password())){
                    session.setAttribute("salesman",salesman);
                    model.addAttribute("salesman",salesman);
                    return "index2";
                }
            }
        }
        model.addAttribute("error","用户名或密码错误！");
        return "login";
//        return "404";
    }
    @RequestMapping("/outLogin")
    public String outLogin(HttpSession session){
        //通过session.invalidata()方法来注销当前的session
        session.invalidate();
        return "login";
    }

    @RequestMapping("/welcome")
    public String welcome(){
        return "welcome";
    }


}